<template>
  <div style="height: 80vh;">
    <div class="person-heart" v-if="userStore.open">
      <el-avatar :src="loginAvatar" :size=100 style="position: relative; top:-20px ;margin: 10px" />
      <div style="width: 100%;">
        <div style="display: flex; justify-content: space-between; width: 100%;">
          <el-text tag="span" style="font-size: 30px;">{{ userStore.name || "默认" }}</el-text>
          <div style=" margin-top: 10px">
            <el-button round :icon="Edit" @click="visibleFrom = true">个人中心</el-button>
            <el-button round :icon="EditPen" @click="visible = true">修改密码</el-button>
          </div>
        </div>
        <el-text style="display: flex; justify-content: start; gap:20px">
          <el-text tag="span">浏览量：10</el-text>
          <el-text tag="span">点赞数：10</el-text>
          <el-text tag="span">原作：10</el-text>
        </el-text>
      </div>
    </div>
    <HomePage :authorId="authorId" />
  </div>
  <el-dialog v-model="visible" :title="titleDialog" width="500" @open="visibleOpen">
    <el-form :model="formData" ref="form" label-width="100px" :rules="rules">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="formData.oldPassword" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="formData.newPassword" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
        <el-button type="primary" @click="alterPassword">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="visibleFrom" title="个人信息" @open="fileList = []">
    <el-form label-width="100px" size="large">
      <el-form-item label="头像">
        <el-upload v-model:file-list="fileList" list-type="picture-card" :on-preview="handlePictureCardPreview"
          :auto-upload="false" :limit="1" :on-remove="handleRemove">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="账号">
        <el-input v-model="user.account"></el-input>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="user.name"></el-input>
      </el-form-item>
      <el-form-item label="用户类型">
        <el-input v-model="typeName" disabled />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visibleFrom = false">关闭</el-button>
      <el-button type="primary" @click="onUser">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { queryUser, changePassword, editUser, editAvatar } from '@/api/modules'
import { useHandleData } from "@/hooks/useHandleData"
import { useUserStore } from '@/stores/use'
import { computed, ref, reactive, watch, onMounted } from 'vue'
import { Edit, EditPen, Plus } from '@element-plus/icons-vue'
import HomePage from "./HomePage.vue"
interface User {
  id: number
  account: string
  name: string
  type: number
}
const userStore = useUserStore()
const user = reactive<User>({ id: 0, account: '', name: '', type: 0 })
const visible = ref(false)
const visibleFrom = ref(false)
const titleDialog = ref('修改密码')
const formData = reactive({
  oldPassword: '',
  newPassword: ''
})
const authorId = ref();
const form = ref()
const rules = {
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }]
}
onMounted(() => {
  userStore.open = true;
})
watch(
  () => userStore.login,
  (newVal) => {
    if (newVal) queryResult()
  }
)
const loginAvatar = computed(() => {
  if (userStore.avatar === '') return "public/avatar.png"
  else return userStore.avatar

})
const typeName = computed(() => user.type === 2 ? '普通用户' : '管理员')
const queryResult = async () => {
  const result = await queryUser(userStore.id)
  Object.assign(user, result.data.data)
  userStore.name = user.name
}
const visibleOpen = () => {
  formData.oldPassword = ''
  formData.newPassword = ''
  form.value.clearValidate()
}
const alterPassword = async () => {
  form?.value?.validate()
  if (!formData.newPassword || !formData.oldPassword) return;
  if (userStore.password !== formData.oldPassword) return;
  const params = { id: user.id, data: { oldPassword: userStore.password, newPassword: formData.newPassword } }
  await useHandleData(changePassword, params, '修改密码', 'success')
  userStore.password = formData.newPassword
  visible.value = false
}
const onUser = () => {
  const params = { id: user.id, data: { account: user.account, name: user.name } }
  useHandleData(editUser, params, "修改个人信息", "success")
  const formDataFile = new FormData();
  if (fileList.value.length < 1 || !fileList.value[0]?.raw) return;
  formDataFile.append('file', fileList.value[0].raw);
  editAvatar(user.id, formDataFile)
  userStore.avatar = fileList.value[0].url!
  visibleFrom.value = false
  userStore.name = user.name;
  userStore.username = user.account;
}

import type { UploadProps, UploadUserFile } from 'element-plus'

const fileList = ref<UploadUserFile[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const handleRemove: UploadProps['onRemove'] = () => {
  fileList.value = []
}
</script>
<style scoped>
.person-heart {
  display: flex;
  background-color: #ffffff;
}
</style>
